<?php

namespace app\shop\controller;

use think\Controller;

class Team extends Controller
{

    // 控制器初始化
    public function _initialize()
    {
        parent::_initialize();
        $this->CommissionModel = model('Business.Commission');
        $this->SubjectModel = model('Subject.Subject');
        $this->BusinessModel = model('Business.Business');
        $this->RecordModel = model('Business.Record');
        $this->AddressModel = model('Business.Address');
        $this->ProductModel = model('Product.Product');
        $this->TeamModel = model('Team.Team');
        $this->OrderBusinessModel = model('Team.OrderBusiness');
        $this->RelationModel = model('Product.Relation');
    }

    // 海报
    public function poster()
    {
        if ($this->request->isPost()) {
            // 获取当前域名
            // 获取协议名
            $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? 'https' : 'http';
            // 获取当前域名
            $domain = $protocol . '://' . $_SERVER['SERVER_NAME'];

            // 获取个人信息
            $id = $this->request->param('busid', 0, 'trim');
            $mobile =  $this->request->param('mobile', 0, 'trim');
            $business = $this->BusinessModel->find($id);
            $token = md5($id . $mobile);

            // 头像
            $avatar = isset($business['avatar_text']) ? trim($business['avatar_text']) : '';

            // 海报底图
            $poster = isset($business['poster_text']) ? trim($business['poster_text']) : '';

            // url('地址表达式',['参数'],['URL后缀'],['域名'])(用于生成二维码)
            // $url = url('business/login', ['token' => $token], false, false);
            // $url = 'http://localhost:5173/#/business/login?token=' . $token; //本地
            $url = 'https://shopm.constqr.cn/#/business/login?token=' . $token; //线上

            // 生成二维码
            if ($this->request->isPost()) {
                // 实例化二维码插件
                $code = new \dh2y\qrcode\QRcode();

                // 设置二维码容错率
                $level = ['L', 'M'];
                $index = array_rand($level);

                // 获取二维码生成的路径
                $code_path = $code->png($url, false, 15, $level[$index])->getPath();

                // 二维码（需要绝对路径）
                $Qrcode = $domain . str_replace('\\', '/', $code_path);

                // var_dump($Qrcode);exit;
                // 做一张海报 创建图片的实例
                $PosterImg = imagecreatefromstring(file_get_contents($poster));
                $QrcodeImg = imagecreatefromstring(file_get_contents($Qrcode));
                $AvatarImg = imagecreatefromstring(file_get_contents($avatar));

                // 创建头像缩略图
                $AvatarThumb = imagecreatetruecolor(100, 100);
                // 重采样拷贝部分图像并调整大小
                imagecopyresampled($AvatarThumb, $AvatarImg, 0, 0, 0, 0, 100, 100, imagesx($AvatarImg), imagesy($AvatarImg));

                // 二维码图片的宽和高 获取新的尺寸
                list($QrcodeW, $QrcodeH) = getimagesize($Qrcode);

                // imagecopymerge — 拷贝并合并图像的一部分
                imagecopymerge($PosterImg, $QrcodeImg, 70, 250, 0, 0, $QrcodeW, $QrcodeH, 100);
                imagecopymerge($PosterImg, $AvatarThumb, 50, 40, 0, 0, 100, 100, 100);

                if ($protocol == 'https') {
                    // 字体文件（线上）（可以相对路径）
                    $font = realpath('assets/fonts/captcha.ttf');
                } else {
                    // 字体文件（本地）（需要绝对路径）
                    $font = 'D:\develop\phpstudy_pro\WWW\thinkphp\1.5.2.20240906\public\assets\fonts\captcha.ttf';
                }

                // 文字昵称放到底图上面
                $black = imagecolorallocate($PosterImg, 0, 0, 0); // 字体颜色
                imagettftext($PosterImg, 20, 0, 180, 70, $black, $font, $business['nickname']);

                //保留的二维码图片文件路径（准备用于删除）
                $PosterPath = "uploads/qrcode/{$token}.jpg";
                $results = imagejpeg($PosterImg, $PosterPath);

                if ($protocol == 'https') {
                } else {
                    //删除二维码图片、释放资源
                    is_file(trim($code_path, '\\')) && @unlink(trim($code_path, '\\'));
                }

                // 释放资源
                imagedestroy($PosterImg);
                imagedestroy($QrcodeImg);
                imagedestroy($AvatarImg);
                imagedestroy($AvatarThumb);

                //没有保留下来
                if (!$results) {
                    $this->error("生成海报失败");
                    exit;
                }

                $data = [
                    'id' => $id,
                    'poster' => '/' . $PosterPath
                ];

                $result = $this->BusinessModel->isUpdate(true)->save($data);

                $Poster = $domain . '/' . $PosterPath;
                $response = [
                    'url' => $url,
                    'poster' => $Poster,
                ];

                if ($result === false) {
                    //将保留下来二维码海报删除掉
                    @is_file($PosterPath) && @unlink($PosterPath);
                    $this->error('更新海报失败');
                    exit;
                } else {
                    //跟头像一样的道理，将旧的删掉
                    //将保留下来二维码海报删除掉
                    $this->success('更新海报成功', null, $response);
                    exit;
                }
            }
        }
    }

    // 提现列表
    public function commission()
    {
        if ($this->request->isPost()) {
            $page = $this->request->param('page', 1, 'trim');
            $status = $this->request->param('status', 3, 'trim');

            $where = [
                'commission.parentid' => $this->Business['id'],
                'type' => 'subject'
            ];

            if ($status != 3) {
                $where['status'] = $status;
            }

            $list = $this->CommissionModel->with(['business', 'order'])->where($where)->page("$page, 10")->order('createtime desc')->select();

            // 总数
            $count = $this->CommissionModel->with(['business', 'order'])->where($where)->count();

            if ($list) {

                foreach ($list as $item) {
                    $subid = isset($item['order']['subid']) ? $item['order']['subid'] : 0;
                    $subject = $this->SubjectModel->find($subid);
                    $item['subject'] = $subject;
                }

                $data = [
                    'count' => $count,
                    'list' => $list
                ];

                $this->success('', '', $data);
            } else {
                $this->error('暂无更多数据');
            }
        }
        return $this->view->fetch();
    }

    //提现功能
    public function recover()
    {
        $comid = $this->request->param('comid', 0, 'trim');

        $commission = $this->CommissionModel->find($comid);

        if (!$commission) {
            $this->error('暂无提现记录');
            exit;
        }

        /*
            佣金记录表： 状态更新
            用户表： 余额更新
            消费记录表： 新增
        */
        $this->CommissionModel->startTrans();
        $this->BusinessModel->startTrans();
        $this->RecordModel->startTrans();

        $CommissionStatus = $this->CommissionModel->where(['id' => $comid])->update(['status' => '1']);

        if ($CommissionStatus === false) {
            $this->error($this->CommissionModel->getError());
            exit;
        }

        // 剩余余额
        $money = bcadd($this->Business['money'], $commission['amount'], 2);

        $BusinessData = [
            'id' => $this->Business['id'],
            'money' => $money
        ];

        $validate = [
            [
                'money' => ['number', 'egt:0'],
            ],
            [
                'money.number'  => '余额必须是数字类型',
                'money.egt'      => '余额不足请先充值',
            ]
        ];

        $BusinessStatus = $this->BusinessModel->validate(...$validate)->isUpdate(true)->save($BusinessData);

        if ($BusinessStatus === false) {
            $this->CommissionModel->rollback();
            $this->error($this->BusinessModel->getError());
            exit;
        }

        $RecordData = [
            'total' => $commission['amount'],
            'busid' => $this->Business['id'],
            'content' => "提现佣金，￥{$commission['amount']}元"
        ];

        $RecordStatus = $this->RecordModel->validate('common/Business/Record')->save($RecordData);
        if ($RecordStatus === false) {
            $this->CommissionModel->rollback();
            $this->BusinessModel->rollback();
            $this->error($this->RecordModel->getError());
            exit;
        }

        if ($CommissionStatus === false || $BusinessStatus === false || $RecordStatus === false) {
            $this->CommissionModel->rollback();
            $this->BusinessModel->rollback();
            $this->RecordModel->rollback();
            $this->error('提现失败');
            exit;
        } else {
            $this->CommissionModel->commit();
            $this->BusinessModel->commit();
            $this->RecordModel->commit();
            $this->success('提现成功');
            exit;
        }
    }

    // 发起拼团
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->param();
            $busid = isset($params['busid']) ? $params['busid'] : 0;
            $addrid = isset($params['addrid']) ? $params['addrid'] : 0;
            $proid = isset($params['proid']) ? $params['proid'] : 0;
            $nums = isset($params['nums']) ? $params['nums'] : 0;
            $pay = isset($params['pay']) ? $params['pay'] : 'money';
            $attrs = isset($params['attrs']) ? $params['attrs'] : '';
            $total = isset($params['total']) ? $params['total'] : 0;

            $business =  $this->BusinessModel->find($busid);

            if (!$business) {
                $this->error('用户不存在');
                exit;
            }

            $address = $this->AddressModel->find($addrid);
            if (!$address) {
                $this->error('收货地址不存在');
                exit;
            }

            $product = $this->ProductModel->find($proid);

            if (!$product) {
                $this->error('拼团商品不存在');
                exit;
            }

            $stock = bcsub($product['stock'], $nums);

            if ($stock < 0) {
                $this->error("{$product['name']}库存不足");
                exit;
            }

            $teaminfo = $this->TeamModel->where(['busid' => $busid, 'proid' => $proid, 'status' => '1'])->find();

            if ($teaminfo) {
                $this->error("已发起拼团，请忽重复发起");
                exit;
            }

            // 余额支付
            if ($pay === 'money') {
                // 开启事务
                $this->TeamModel->startTrans();
                $this->OrderBusinessModel->startTrans();
                $this->BusinessModel->startTrans();
                $this->RecordModel->startTrans();

                $endtime = time() + 86400 * 2;

                $TeamData = [
                    'busid' => $busid,
                    'total' => 5,
                    'proid' => $proid,
                    'status' => '1',
                    'endtime' => $endtime,
                ];

                $TeamStatus = $this->TeamModel->save($TeamData);

                if ($TeamStatus === false) {
                    $this->error($this->TeamModel->getError());
                    exit;
                }

                $OrderBusinessData = [
                    'teamid' => $this->TeamModel->id,
                    'busid' => $busid,
                    'addrid' => $addrid,
                    'proid' => $proid,
                    'total' => isset($params['total']) ?? 0,
                    'remark' => isset($params['remark']) ?? '',
                    'nums' =>  $nums,
                    'pay' => $pay,
                ];

                // 查询商品属性信息  
                $Relationlist = $this->RelationModel->with('prop')->where('relation.id', 'IN', $attrs)->select();

                // 商品属性
                if ($Relationlist) {
                    $attrslist = [];

                    // 商品价格
                    $price = $product['buy'];

                    foreach ($Relationlist as $item) {
                        $attrslist[] = [
                            'title' => $item['prop']['title'], // 商品属性名
                            'value' => $item['value'], // 属性名称
                            'price' => $item['price'] // 价格
                        ];

                        $price = bcadd($price, $item['price'], 2);
                    }

                    $OrderBusinessData['price'] = $price;
                    $OrderBusinessData['attrs'] = json_encode($attrslist);
                } else {
                    $OrderBusinessData['price'] = $product['buy'];
                    $OrderBusinessData['attrs'] = null;
                }

                // 校验器 拼团人员名单表
                $OrderBusinessStatus = $this->OrderBusinessModel->save($OrderBusinessData);

                if ($OrderBusinessStatus === false) {
                    $this->TeamModel->rollback();
                    $this->error($this->OrderBusinessModel->getError());
                    exit;
                }

                // 剩余余额
                $money = bcsub($business['money'], $total, 2);

                $BusinessData = [
                    'id' => $busid,
                    'money' => $money
                ];

                $validate = [
                    [
                        'money' => ['number', 'egt:0'],
                    ],
                    [
                        'money.number'  => '余额必须是数字类型',
                        'money.egt'      => '余额不足请先充值',
                    ]
                ];

                // 用户表
                $BusinessStatus = $this->BusinessModel->validate(...$validate)->isUpdate(true)->save($BusinessData);

                if ($BusinessStatus === false) {
                    $this->TeamModel->rollback();
                    $this->OrderBusinessModel->rollback();
                    $this->error($this->BusinessModel->getError());
                    exit;
                }

                $RecordData = [
                    'total' => $total,
                    'busid' => $busid,
                    'content' => $product['name'] . "商品拼团订单---消费的金额：" . $total . " 元"
                ];

                // 消费记录表
                $RecordStatus = $this->RecordModel->validate('common/Business/Record')->save($RecordData);
                if ($RecordStatus === false) {
                    $this->TeamModel->rollback();
                    $this->OrderBusinessModel->rollback();
                    $this->BusinessModel->rollback();
                    $this->error($this->RecordModel->getError());
                    exit;
                }

                if ($TeamStatus === false || $OrderBusinessStatus === false || $BusinessStatus === false || $RecordStatus === false) {
                    $this->TeamModel->rollback();
                    $this->OrderBusinessModel->rollback();
                    $this->BusinessModel->rollback();
                    $this->RecordModel->rollback();
                    $this->error('发起拼团失败');
                } else {
                    $this->TeamModel->commit();
                    $this->OrderBusinessModel->commit();
                    $this->BusinessModel->commit();
                    $this->RecordModel->commit();
                    $this->success('发起拼团成功');
                }
            }
        }
    }

    // 拼团列表
    public function index()
    {
        if ($this->request->isPost()) {

            $data = $this->TeamModel->with('product')->where(['team.status' => '1'])->order('createtime desc')->select();

            $this->success('', '', $data);
        }
    }

    // 拼团详情
    public function info()
    {
        if ($this->request->isPost()) {
            $teamid = $this->request->param('teamid', 0, 'trim');

            $teaminfo = $this->TeamModel->with('product')->where(['team.status' => '1'])->find($teamid);

            if (!$teaminfo) {
                $this->error('拼团订单不存在');
            }

            $teamlist = $this->OrderBusinessModel->with('business')->where(['teamid' => $teamid])->select();

            $data = [
                'teaminfo' => $teaminfo,
                'teamlist' => $teamlist
            ];

            $this->success('', '', $data);
        }
    }

    // 参与拼团
    public function join()
    {
        if ($this->request->isPost()) {
            $params = $this->request->param();
            $busid = isset($params['busid']) ? $params['busid'] : 0;
            $addrid = isset($params['addrid']) ? $params['addrid'] : 0;
            $proid = isset($params['proid']) ? $params['proid'] : 0;
            $nums = isset($params['nums']) ? $params['nums'] : 0;
            $pay = isset($params['pay']) ? $params['pay'] : 'money';
            $attrs = isset($params['attrs']) ? $params['attrs'] : '';
            $total = isset($params['total']) ? $params['total'] : 0;
            $teamid = isset($params['teamid']) ? $params['teamid'] : 0;

            $business =  $this->BusinessModel->find($busid);

            if (!$business) {
                $this->error('用户不存在');
                exit;
            }

            $address = $this->AddressModel->find($addrid);
            if (!$address) {
                $this->error('收货地址不存在');
                exit;
            }

            $product = $this->ProductModel->find($proid);

            if (!$product) {
                $this->error('拼团商品不存在');
                exit;
            }

            $stock = bcsub($product['stock'], $nums);

            if ($stock < 0) {
                $this->error("{$product['name']}库存不足");
                exit;
            }

            $teaminfo = $this->TeamModel->where(['proid' => $proid, 'status' => '1'])->find();

            if (!$teaminfo) {
                $this->error("该商品未发起拼团，请先发起拼团");
                exit;
            } else if ($teamid == 0) {
                $teamid = $teaminfo['id'];
            }

            // 余额支付
            if ($pay === 'money') {
                // 开启事务
                $this->TeamModel->startTrans();
                $this->OrderBusinessModel->startTrans();
                $this->BusinessModel->startTrans();
                $this->RecordModel->startTrans();

                $OrderBusinessData = [
                    'teamid' => $teamid,
                    'busid' => $busid,
                    'addrid' => $addrid,
                    'proid' => $proid,
                    'total' => isset($params['total']) ?? 0,
                    'remark' => isset($params['remark']) ?? '',
                    'nums' =>  $nums,
                    'pay' => $pay,
                ];

                // 查询商品属性信息  
                $Relationlist = $this->RelationModel->with('prop')->where('relation.id', 'IN', $attrs)->select();

                // 商品属性
                if ($Relationlist) {
                    $attrslist = [];

                    // 商品价格
                    $price = $product['buy'];

                    foreach ($Relationlist as $item) {
                        $attrslist[] = [
                            'title' => $item['prop']['title'], // 商品属性名
                            'value' => $item['value'], // 属性名称
                            'price' => $item['price'] // 价格
                        ];

                        $price = bcadd($price, $item['price'], 2);
                    }

                    $OrderBusinessData['price'] = $price;
                    $OrderBusinessData['attrs'] = json_encode($attrslist);
                } else {
                    $OrderBusinessData['price'] = $product['buy'];
                    $OrderBusinessData['attrs'] = null;
                }

                // 检查是否已经参与过
                $checkJoin = $this->OrderBusinessModel->where(['teamid' => $teamid, 'busid' => $busid])->find();
                if ($checkJoin) {
                    $this->error('您已经参与过该拼团，请勿重复参与');
                    exit;
                }

                // 校验器 拼团人员名单表
                $OrderBusinessStatus = $this->OrderBusinessModel->save($OrderBusinessData);

                if ($OrderBusinessStatus === false) {
                    $this->error($this->OrderBusinessModel->getError());
                    exit;
                }

                // 检查拼团是否结束
                $TeamStatus = true;
                $orderBusinessCount = $this->OrderBusinessModel->where(['teamid' => $teamid])->count();
                if ($orderBusinessCount == false) {
                    $this->OrderBusinessModel->rollback();
                    $this->error('拼团订单不存在' . $this->OrderBusinessModel->getError());
                    exit;
                }
                if ($orderBusinessCount == $teaminfo['total']) {
                    $teaminfo['status'] = '0';
                    $TeamStatus = $this->TeamModel->isUpdate(true)->save($teaminfo);
                    if ($TeamStatus === false) {
                        $this->OrderBusinessModel->rollback();
                        $this->error($this->TeamModel->getError());
                        exit;
                    }
                }

                // 剩余余额
                $money = bcsub($business['money'], $total, 2);

                $BusinessData = [
                    'id' => $busid,
                    'money' => $money
                ];

                $validate = [
                    [
                        'money' => ['number', 'egt:0'],
                    ],
                    [
                        'money.number'  => '余额必须是数字类型',
                        'money.egt'      => '余额不足请先充值',
                    ]
                ];

                // 用户表
                $BusinessStatus = $this->BusinessModel->validate(...$validate)->isUpdate(true)->save($BusinessData);

                if ($BusinessStatus === false) {
                    $this->OrderBusinessModel->rollback();
                    $this->TeamModel->rollback();
                    $this->error($this->BusinessModel->getError());
                    exit;
                }

                // 组装消费记录表新增数据
                $RecordData = [
                    'total' => $total,
                    'busid' => $busid,
                    'content' => $product['name'] . "商品拼团订单---消费的金额：" . $total . " 元"
                ];
                // 消费记录表
                $RecordStatus = $this->RecordModel->validate('common/Business/Record')->save($RecordData);
                if ($RecordStatus === false) {
                    $this->OrderBusinessModel->rollback();
                    $this->TeamModel->rollback();
                    $this->BusinessModel->rollback();
                    $this->error($this->RecordModel->getError());
                    exit;
                }

                if ($TeamStatus === false || $OrderBusinessStatus === false || $BusinessStatus === false || $RecordStatus === false) {
                    $this->OrderBusinessModel->rollback();
                    $this->TeamModel->rollback();
                    $this->BusinessModel->rollback();
                    $this->RecordModel->rollback();
                    $this->error('参与拼团失败');
                } else {
                    $this->OrderBusinessModel->commit();
                    $this->TeamModel->commit();
                    $this->BusinessModel->commit();
                    $this->RecordModel->commit();
                    $this->success('参与拼团成功');
                }
            }
        }
    }
}
